package com.houdoudou.customer;



import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;


import com.houdoudou.bean.Customer;
import com.houdoudou.bean.Machine;
import com.houdoudou.customer.common.CommonFunction;
import com.houdoudou.customer.common.Constant;
import com.houdoudou.customer.common.ImageText;
import com.houdoudou.customer.common.UniversalHttpPost;
import com.houdoudou.customer.me.LoginAct;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;


public class CustomerMainActivity extends FragmentActivity {
    
	

	public static Handler mainHandler;
     FragmentManager myFragmentMan ;
	 Fragment current_frg,buy_frg,order_frg,find_frg,me_frg;
	 LinearLayout bottomPanel = null;  
	 private ImageText mBuyBtn = null;  
     private ImageText mOrderBtn = null;  
	 private ImageText  mFindBtn = null;  
	 private ImageText mMeBtn = null;  
	 ImageView  welcome;
	 View.OnClickListener myOnClicListener;
	 public static String currFragTag = "";
	 private int DEFALUT_BACKGROUND_COLOR = Color.rgb(243, 243, 243);  
	 private long exitTime = 0;
     boolean showWelcome=true;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_customer_main);
		
		 init_Listener();
		 init_componet();
		 recover_bottom_bar();
		 init_handler();
		System.out.println("---------MainActivity OnCreat----------------");
		myFragmentMan = getSupportFragmentManager();
	      checkNetAndStart();
	   
	}

    @Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.customer_main, menu);
		return true;
	}
	
	private void init_handler(){
		mainHandler= new Handler(){

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				if(msg.what==1){
					welcome.setVisibility(View.GONE);
					Constant.showWelcome=false;
				}
				
				super.handleMessage(msg);
			}
			
		};
	}
     private void init_componet(){
    	   bottomPanel =  (LinearLayout) findViewById(R.id.bottom_layout);  
    	 
    	    mBuyBtn = (ImageText)findViewById(R.id.btn_buy_act_main);  
	        mOrderBtn = (ImageText)findViewById(R.id.btn_order_act_main);  
	         mFindBtn = (ImageText)findViewById(R.id.btn_find_act_main);  
	        mMeBtn = (ImageText)findViewById(R.id.btn_me_act_main);  
	        welcome= (ImageView) findViewById(R.id.img_welcome_act_main);
	        if(Constant.showWelcome){welcome.setVisibility(View.VISIBLE);}else{ welcome.setVisibility(View.GONE);}
	        
	        bottomPanel.setBackgroundColor(DEFALUT_BACKGROUND_COLOR);  
	        
	        mBuyBtn.setOnClickListener(myOnClicListener);
	        mOrderBtn.setOnClickListener(myOnClicListener);
	        mFindBtn.setOnClickListener(myOnClicListener);
	        mMeBtn.setOnClickListener(myOnClicListener);
	        
	        mBuyBtn.setText("购买");
	        mOrderBtn.setText("订单");
	        mMeBtn.setText("我的");
	        mFindBtn.setText("发现");
	        
	       
	    
     }
     
     private void recover_bottom_bar(){
    	 mBuyBtn.setImage(R.drawable.buy_unselected);  
         mBuyBtn.setTextChoosed(false);
         mOrderBtn.setImage(R.drawable.order_unselected);  
         mOrderBtn.setTextChoosed(false);
         mFindBtn.setImage(R.drawable.find_unselected);  
         mFindBtn.setTextChoosed(false);         
         mMeBtn.setImage(R.drawable.me_unselected);  
         mMeBtn.setTextChoosed(false);
        
         
     }
      
	 private void init_Listener() {  
	        // TODO Auto-generated method stub  
		//  System.out.println("------imgeTextId-------"+imgeTextId);
	    myOnClicListener= new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				recover_bottom_bar();
			    switch(v.getId()){
                case R.id.btn_buy_act_main:{
 	                      if(buy_frg==null) buy_frg= new FrgBuyOfActMain();
 	                      switchContent(buy_frg);
 	                      mBuyBtn.setImage(R.drawable.order_selected);  
 	                      mBuyBtn.setTextChoosed(true);
                             break;}
                case R.id.btn_order_act_main:{
                    if(order_frg==null) order_frg= new FrgOrderOfActMain();
                    switchContent(order_frg);
                    mOrderBtn.setImage(R.drawable.order_selected);  
                    mOrderBtn.setTextChoosed(true);
                      break;}
                case R.id.btn_find_act_main:{
                    if(find_frg==null) find_frg= new FrgFindOfActMain();
                    switchContent(find_frg);
                    mFindBtn.setImage(R.drawable.find_selected);  
                    mFindBtn.setTextChoosed(true);
                      break;}
                case R.id.btn_me_act_main:{
                    if(me_frg==null) me_frg= new FrgMeOfActMain();
                    switchContent(me_frg);
                    mMeBtn.setImage(R.drawable.me_selected);  
                    mMeBtn.setTextChoosed(true);
                      break;}
    }
			}
		};
		      
	    }  
	  public void switchContent(Fragment to) {
		   FragmentTransaction transaction = myFragmentMan.beginTransaction();
		   if(current_frg==null){
			   current_frg = to;
			   transaction.replace(R.id.fragment_content, current_frg).commit();
			 
		   }else if (current_frg!= to){
	         
	          //  FragmentTransaction transaction = myFragmentMan.beginTransaction().setCustomAnimations(
	            //        android.R.anim.fade_in, android.R.anim.fade_out);
	         
	            if (!to.isAdded()) {    // 先判断是否被add过
	                transaction.hide(current_frg).add(R.id.fragment_content, to).commit(); // 隐藏当前的fragment，add下一个到Activity中
	            } else {
	                transaction.hide(current_frg).show(to).commit(); // 隐藏当前的fragment，显示下一个
	            }
	        current_frg = to;  
		   }
		   
	    }
	  
	  private void checkNetAndStart(){
		  if(CommonFunction.isNetworkAvailble(CustomerMainActivity.this)){
				app_config(); 
			  }else{
				  welcome.setVisibility(View.GONE);		  
				  Builder b = new AlertDialog.Builder(CustomerMainActivity.this).setTitle("没有可用的移动网络和wifi")  
						     .setMessage("是否对网络进行设置？");  
						   b.setPositiveButton("设置网络", new DialogInterface.OnClickListener() {  
						    public void onClick(DialogInterface dialog, int whichButton) {  					    	
						    	Intent mIntent = new Intent(Settings.ACTION_SETTINGS); 
						          startActivity(mIntent);   
						    }  
						   }).setNeutralButton("重试",new DialogInterface.OnClickListener() {  
							    public void onClick(DialogInterface dialog, int whichButton) {  
								   checkNetAndStart();    
								   
								    }  
						   }).setNegativeButton("离线使用",new DialogInterface.OnClickListener() {  
							    public void onClick(DialogInterface dialog, int whichButton) {  
								   app_config();   dialog.cancel();   
								   
								    }  
						   }).show();  
			  }
	  }
	  private void app_config(){
		  
		  SharedPreferences sharedPreferences = CustomerMainActivity.this.getSharedPreferences("config", Context.MODE_PRIVATE);
		  Editor editor = sharedPreferences.edit();   
		  boolean base_empty=false,owner_empty=false;
		
		  if(sharedPreferences.getString("BaseUrl", "").isEmpty()) base_empty=true;
	       if(sharedPreferences.getString("CustomerUrl", "").isEmpty()) owner_empty=true;
	       if(base_empty||owner_empty){
	    	  System.out.println("-------------BaseUrl empty-----------");
	    	   editor.putString("BaseUrl", "http://192.168.1.115"); 
	    	   editor.putString("CustomerUrl", ":8080/houdoudou/customer4App");
	       }
	       editor.commit(); 
	       //可能上次提交未更新 重定义。
	       SharedPreferences sharedPreferences2 = CustomerMainActivity.this.getSharedPreferences("config", Context.MODE_PRIVATE);
	       Constant.BaseUrl=sharedPreferences2.getString("BaseUrl", "");
	       Constant.CustomerUrl=sharedPreferences2.getString("CustomerUrl", "");  
	       String machineStr=sharedPreferences2.getString("machine", "");
	       if(!machineStr.isEmpty()){ Constant.machineJO=JSONObject.fromObject(machineStr); }
	       mBuyBtn.performClick();
	       String customerStr=sharedPreferences2.getString("customer", "");
	       if(!customerStr.isEmpty()){
	    	   JSONObject customerJO=JSONObject.fromObject(customerStr); 
	    	   Constant.customerJO=customerJO;
	    		String[] params= new String[3];
	            params[0]=Constant.BaseUrl+Constant.CustomerUrl;
	            params[1]="login"; //PostCod
	            JSONObject jsonData=new JSONObject();			    		  		        
	            jsonData.put(Customer.TELNUM, customerJO.getString(Customer.TELNUM));	
	        	jsonData.put(Customer.SECRET, customerJO.getString(Customer.SECRET));
	        	params[2]=jsonData.toString();
	            new HttpPostTaskforStart().execute(params);     
	       }	     
           
	  }
	  
	  @Override
	  public boolean onKeyDown(int keyCode, KeyEvent event) {
	      if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){   
	          if((System.currentTimeMillis()-exitTime) > 2000){  
	              Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();                                
	              exitTime = System.currentTimeMillis();   
	          } else {
	              finish();
	              System.exit(0);
	          }
	          return true;   
	      }
	      return super.onKeyDown(keyCode, event);
	  }
	  
	  private  class HttpPostTaskforStart extends android.os.AsyncTask<String,String,Map<String,Object>>{

			

			@Override
			protected Map<String,Object> doInBackground(String... params) {
				// TODO Auto-generated method stub
				 Map<String,Object> map = new HashMap<String ,Object>();		
			      map =	UniversalHttpPost.doPost(params);	             
				return map;
			}
			
			@Override
			protected void onPostExecute(Map<String,Object> map) {
			
				 System.out.println("----------- Customer AUTO Login onPostExecute()--------------");
				 String PostResult=(String) map.get("PostResult");		 
				 boolean networkstate=(Boolean) map.get("PostState");
				 String affair="";
				 Boolean success=false;
			   	 String errorInfo="";
				 JSONObject json = null;		
				   if(!networkstate){ return ; }
				   
			    	Toast.makeText(CustomerMainActivity.this, "StartApp,服务器返回数据为"+PostResult, Toast.LENGTH_SHORT).show();						
					try{
				     json= JSONObject.fromObject(PostResult);
					 success=json.getBoolean("success");
					 errorInfo=json.getString("errorInfo");	
					 affair= json.getString("affair");
					}catch(JSONException e){
						return;
					}
											   												      		       
			         if(!success){ return;}    
			    	
			    		 Constant.customerJO=json.getJSONObject("customer"); 
			    		 SharedPreferences sp = CustomerMainActivity.this.getSharedPreferences("config", Context.MODE_PRIVATE);
			   		     Editor editor = sp.edit();  
			   		     editor.putString("customer", Constant.customerJO.toString());
			   		     editor.commit();
			
			} //onPostExecute
		} //AsyncTask
		  
}
